package org.waldev.multi;

import org.waldev.multi.Multitouch.Table;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class Threads extends Thread{
	SurfaceHolder surfaceHolder;
	private Table table;

	private Canvas c;
	private boolean isRunning = true;
	private boolean isPaused = false;
	private long sleepTime = 0;
	private long delay = 45;

	public Threads(SurfaceHolder surfaceHolder, Table panel)
	{
		this.surfaceHolder = surfaceHolder;
		this.table = panel;
	}

	public void setRunning(boolean run){
		isRunning = run;
	}

	public boolean getRunning(){
		return isRunning();
	}

	public SurfaceHolder getSurface(){
		return surfaceHolder;
	}

	@Override
	public void run(){
		while(isRunning){
			c = null;
			long beforeTime = System.nanoTime();
			try 
			{
				c = surfaceHolder.lockCanvas(null);
				synchronized (surfaceHolder) 
				{
					if(c != null)
					{
						table.onDraw(c);
					}
				}
			} 
			finally 
			{
				// do this in a finally so that if an exception is thrown
				// during the above, we don't leave the Surface in an
				// inconsistent state
				if (c != null) 
				{
					surfaceHolder.unlockCanvasAndPost(c);
				}
			}
			this.sleepTime = delay-((System.nanoTime()-beforeTime)/1000000L);
			//System.out.println(sleepTime);
			try 
			{
				if(sleepTime > 0)
				{
					Thread.sleep(sleepTime);
				}
			} 
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
		}
	}
	public boolean isRunning() {
		return isRunning;
	}
}
